<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <link rel="icon" href="/favicon.ico" />
    <link rel="stylesheet" href="/assets/vendor/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="/assets/style/global.css" />
    <title>文件下载</title>
  </head>
  <body>
    <div id="app" class="app">
      <div class="container">
        <h2 class="text-center">文件下载</h2>
      </div>
      <div class="container">
        <form>
          <div class="form-group">
            <label for="exampleInputFile">链接文件:</label>
            <input id="file" class="form-control-file" type="file" />
          </div>
          <div class="form-group">
            <label for="exampleInputFile">进度:</label>
            <div class="progress">
              <div id="progress" class="progress-bar" role="progressbar" style="width: 0%"></div>
            </div>
          </div>
          <button id="upload" type="button" class="btn btn-primary">上传</button>
          <button id="download" type="button" class="btn btn-primary">下载</button>
        </form>
      </div>
    </div>
    <script>
      let file, fileData
      // 获取 input file 的 dom 对象
      const inputFile = document.querySelector('#file')
      // 监听 change 事件
      inputFile.addEventListener('change', function() {
        file = this.files[0]
        document.querySelector('#progress').style.width = '0%'
      })

      // 上传文件
      document.querySelector('#upload').addEventListener('click', function () {
        if (!file) {
          alert('请选择文件')
          return false
        }
        upload({ file })
      }, false)

      // 上传
      const upload = ({ file } = {}) => {
        let formData = new FormData()
        formData.append('file', file)
        const xhr = new XMLHttpRequest()
        // 监听文件上传进度
        xhr.upload.addEventListener('progress', function(e) {
          if (e.lengthComputable) {
            // 获取进度
            const progress = Math.round((e.loaded * 100) / e.total)
            document.querySelector('#progress').style.width = progress + '%'
          }
        }, false)
        // 监听上传完成事件
        xhr.addEventListener('load', () => {
          console.log(':smile:上传完成')
        }, false)
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4 && xhr.status >= 200) {
            let text = xhr.responseText
            try {
              let res = /{|\[/.test(text) ? JSON.parse(text) : {}
              fileData = res.data || null
            } catch (e) {
              fileData = null
            }
          }
        }
        xhr.open('post', '/upload')
        xhr.send(formData)
      }

      // 下载文件
      document.querySelector('#download').addEventListener('click', function () {
        if (!fileData) {
          alert('请上传链接文件')
          return false
        }
        download(fileData)
      }, false)

      // 下载
      const download = (fileData) => {
        const xhr = new XMLHttpRequest()
        // 监听上传完成事件
        xhr.addEventListener('load', () => {
          console.log(':smile:下载完成')
        }, false)
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4 && xhr.status >= 200) {
            let text = xhr.responseText
            try {
              let res = /{|\[/.test(text) ? JSON.parse(text) : {}
              fileData = res.data || null
            } catch (e) {
              fileData = null
            }
          }
        }
        xhr.open('post', '/download')
        xhr.send(JSON.stringify(fileData))
      }
    </script>
  </body>
</html>